import { _decorator, Collider2D, Component, Contact2DType, IPhysics2DContact, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('bulletAIP')
export class bulletAIP extends Component {
    @property
    speed: number = 880;





    private _collider: Collider2D | null = null;
    private _destroyed: boolean = false;    // 标志防止重复销毁


    start() {
        this._collider = this.getComponent(Collider2D);
        if (this._collider) {
            this._collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        } else {
            console.error('Collider2D 组件未找到');
        }
    }   

    update(deltaTime: number) {
        console.log('bulletAIP update');
        if (this._destroyed) return;
        
        const position = this.node.position;
        this.node.setPosition(position.x, position.y + this.speed * deltaTime, position.z);
        
        if (position.y > 650) {
            this.safeDestroy();
        }

        
    }
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if (this._destroyed) return;
        
        this.safeDestroy();
        // if (otherCollider.node.getComponent('eNemyAPI')) {
        //     this.safeDestroy();
        // }
    }

    private safeDestroy() {

        if (this._destroyed) return;
        this._destroyed = true;
        
        if (this._collider) {
            this._collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            this._collider.enabled = false;
        }
        
        this.scheduleOnce(() => {
            if (this.node && this.node.isValid) {
                this.node.destroy();
            }
        }, 0.02); // 延迟一帧销毁
    }


   onDestroy() {
        this.safeDestroy();
    }
    
}

